 

import { ref, onMounted, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  querySimpleList,
  queryProcessDefinitionByCode
} from '@/service/modules/process-definition'
import { useTaskNodeStore } from '@/store/project/task-node'
import type { IJsonItem } from '../types'
import {
  getWorkPublishListReq,
  delTaskReq
} from '@/service/modules/work-publish'


export function useProcessDefinition({
  model,
  projectCode,
  isCreate,
  from,
  processName,
  taskCode
}: {
  model: { [field: string]: any }
  projectCode: number
  isCreate: boolean
  from?: number
  processName?: number
  taskCode?: number
}): IJsonItem {
  const { t } = useI18n()
  const taskStore = useTaskNodeStore()
  const options = ref([] as { label: string; value: string }[])
  const loading = ref(false)

  const getProcessList = async () => {
    // if (loading.value) return
    // loading.value = true
    // const res = await querySimpleList(projectCode)
    // options.value = res.map((option: { name: string; code: number }) => ({
    //   label: option.name,
    //   value: option.code
    // }))
    const state = reactive({
      page: 1,
      limit: 1000,
      count: 0,
      searchParam: {
        taskType: null,
        name: '',
        departmentId: null
      },
      loading: false,
    })
    state.searchParam.taskType = model.taskType
    const { data, count } = await getWorkPublishListReq({
      page: state.page,
      limit: state.limit,
      ...state.searchParam
    })
    if (!data) throw Error()
    let a  = data.reduce((acc:any,pre:any) =>{
         let temObj = {
          label: pre.name || '作业名',
          value: pre.id 
         } 
         acc.push(temObj)
        return acc
    },[])
    //  options.value = data.map((option: { name: string; code: number }) => ({
    //   label: option.name,
    //   value: option.id
    // }))
    options.value  = a

    console.log(' options.value ',  options.value )

    loading.value = false
  }
  const getProcessListByCode = async (processCode: number) => {
    if (!processCode) return
    const res = await queryProcessDefinitionByCode(processCode, projectCode)
    model.definition = res
    taskStore.updateDefinition(res, taskCode)
  }

  const onChange = (code: number) => {
    // getProcessListByCode(code)
  }

  onMounted(() => {
    if (from === 1 && processName) {
      getProcessListByCode(processName)
    }
    getProcessList()
  })

  return {
    type: 'select',
    field: 'taskDefinitionId',
    span: 24,
    name: t('project.node.work_name'),
    props: {
      loading: loading,
      disabled: !isCreate,
      'on-update:value': onChange
    },
    validate: {
      trigger: ['input', 'blur'],
      required: true,
      validator(validate: any, value: string) {
        if (!value) {
          return new Error(t('project.node.work_name_tips'))
        }
      }
    },
    options: options
  }
}
